# Data Model for news

from django.db import models
from django.contrib import admin


class ViewableManager(models.Manager):
    """
    Filter for unpublished articles.
    """
    def get_query_set(self):
        default_queryset = super(ViewableManager, self).get_query_set()
        return default_queryset.filter(status=1)


class Tag(models.Model):
    """
    Tag is Many to Many with Article object
    """
    name = models.CharField(blank=True, max_length=50, unique=True)
    slug = models.SlugField(unique=True)

    class Meta:
        ordering = ('name',)

    def __unicode__(self):
        return self.name

class TagAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}
    list_display = ('name', 'slug')

admin.site.register(Tag, TagAdmin)


class Category(models.Model):
    """
    one category matches many articles
    """
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(unique=True)

    class Meta:
        verbose_name_plural='Categories'
        ordering = ('name',)

    def __unicode__(self):
        return self.name

class CategoryAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}
    list_display = ('name', 'slug')

admin.site.register(Category, CategoryAdmin)


class Article(models.Model):
    """
    Content for news article.
    """
    STATUS_CHOICE = (
        (0, "Needs Edit"),
        (1, "Published"),
    )

    # article identifier, important
    identifier = models.IntegerField(editable=False)

    # article infomations
    title = models.CharField(max_length=100)
    category = models.ForeignKey(Category)
    tag = models.ManyToManyField(Tag)
    content = models.TextField()
    status = models.IntegerField(choices=STATUS_CHOICE, default=0)
    time = models.DateTimeField()

    # writer infomations
    author = models.CharField(max_length=100)
    email = models.EmailField()
    homepage = models.URLField()
    ip = models.IPAddressField(editable=False)

    class Meta:
        ordering = ('-time',)

    def get_tag_count(self):
        return self.tag.all().count()

    def get_tag(self):
        return self.tag.all()

    def get_latest(self):
        return Article.objects.all()[:10]

    def get_month(self):
        return Aritcle.objects.dates('created', 'month', order='DESC')[:10]

    def save(self):
        #TODO: z: sth must be done with identifier & ip
        import random
        self.identifier = random.randint(0,100)
        self.ip = (str(random.randint(0,255)) + '.') * 3 + str(random.randint(0,255))
        super(Article, self).save()

    admin_objects = models.Manager()
    objects = ViewableManager()

class ArticleAdmin(admin.ModelAdmin):
    filter_horizontal = ('tag',)
    list_display = ('title', 'identifier', 'author', 'category', 'status', 'time')
    search_fields = ('title', 'category', 'content')

admin.site.register(Article, ArticleAdmin)


